import sys
import time
import socket
import select

# 创建一个UDP套接字
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 绑定到一个地址和端口
server_address = ("localhost", 10000)
sock.bind(server_address)

# 初始化等待客户端的列表
inputs = [sock, sys.stdin]
client_addr = None
print("UDP Echo服务器已启动，等待客户端连接...")
while True:
    # 使用select()等待套接字输入
    readable, _, _ = select.select(inputs, [], [])

    # 遍历所有可读的套接字
    for s in readable:
        if s == sock:
            # 如果是服务器套接字，则接收客户端数据
            data, client_addr = sock.recvfrom(4096)
            print(f"收到来自{client_addr}的数据: {data}")
            # 回显接收到的数据
            sock.sendto(data, client_addr)
        elif s == sys.stdin:
            buf = sys.stdin.readline().strip()
            if buf == "q":
                break
            print(f"input: {buf}")
            if client_addr:
                sock.sendto(buf.encode(), client_addr)
        else:
            print("客户端已断开连接")
            inputs.remove(s)
